import { useState, useEffect } from "react";
import axios from "axios";
import { message, Modal } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
const { confirm } = Modal;
function usePublish(type) {
  const [dataSource, setdataSource] = useState([]);
  const { username } = JSON.parse(localStorage.getItem("token"));
  useEffect(() => {
    axios
      .get(`/news?_expand=category&author=${username}&publishState=${type}`)
      .then(({ data }) => {
        setdataSource(data);
      });
  }, [username, type]);
  const handlePublish = id => {
    setdataSource(dataSource.filter(v => v.id !== id));
    axios
      .patch(`/news/${id}`, {
        publishState: 2
      })
      .then(() => {
        message.success("发布成功！");
      });
  };
  const handleSunset = id => {
    setdataSource(dataSource.filter(v => v.id !== id));
    axios
      .patch(`/news/${id}`, {
        publishState: 3
      })
      .then(() => {
        message.success("下线成功！");
      });
  };
  const handleDelete = id => {
    confirm({
      title: "您确定删除该新闻吗?",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        setdataSource(dataSource.filter(v => v.id !== id));
        axios.delete(`/news/${id}`).then(() => {
          message.success("删除成功！");
        });
      },
      onCancel() {}
    });
  };
  return {
    dataSource,
    handlePublish,
    handleSunset,
    handleDelete
  };
}
export default usePublish;
